//
//  InformationViewController.m
//  Business Club
//
//  Created by 范琦 on 16/4/7.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "InformationViewController.h"
#import "PhotosAndLB.h"
#import "InformationModel.h"
#import "InformationCell.h"
#import "UIImageView+WebCache.h"
#import "InformationDetailViewController.h"
#import "InformationCell2.h"


@interface InformationViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSString *token;
    NSString *page;
    UIAlertView *aler;
}

@property (nonatomic, strong) PhotosAndLB *scroll;             //上方的scrollView
@property (nonatomic, strong) UIPageControl *pageControl;       // pageControl
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) NSMutableArray *tapArr;
@property (nonatomic, strong) NSMutableArray *idArr;

@end

@implementation InformationViewController
- (void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];


}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    token = [NSUSERDEFAULTS objectForKey:@"gettoken"];
    [self creatView];
    self.listArr = [NSMutableArray array];

    [self setupRefresh];
    page = @"1";
    
}
- (void)creatView
{
    self.scroll = [[PhotosAndLB alloc]initWithFrame:CGRectMake(0, 20, KSCREENWIDTH, KSCREENHEIGHT / 5)];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, KSCREENWIDTH, KSCREENHEIGHT - self.tabBarController.tabBar.frame.size.height - KSCREENHEIGHT / 11) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    self.tableView.tableHeaderView = _scroll;
    
    _tableView.sectionFooterHeight = 0;
    [_tableView registerNib:[UINib nibWithNibName:@"InformationCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [_tableView registerNib:[UINib nibWithNibName:@"InformationCell2" bundle:nil] forCellReuseIdentifier:@"cell2"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
    });


}


- (void)netHandle
{
    
    // 轮播的网络请求
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:[NSString stringWithFormat:@"/Zx/hots.html?token=%@",token] RegisterApiMethod:RequestMethodGet];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        id result = [request.responseBody objectForKey:@"result"];
        NSArray *arr = [result objectForKey:@"data"];
        NSMutableArray *imagesArr = [NSMutableArray array];
        NSMutableArray *labelArr = [NSMutableArray array];
        self.idArr = [NSMutableArray array];
        self.tapArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            [imagesArr addObject:dic[@"img"]];
            [labelArr addObject:dic[@"name"]];
            [_idArr addObject:dic[@"id"]];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageV:)];
            [_tapArr addObject:tap];
            
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageV:)];
        
        [_tapArr addObject:tap];

        [_scroll setArr:[NSMutableArray arrayWithArray:imagesArr] photoStyles:PhotosNet placeholderImage:@"" pageControl:CGRectMake(KSCREENWIDTH - (imagesArr.count * 30), _scroll.bounds.size.height - 20, imagesArr.count * 30, 20)];
        [_scroll setImageGestureRecognizers:_tapArr];
        [_scroll setLabelArr:labelArr];

    } failure:^(YTKBaseRequest *request) {
        
    }];
    
    // 列表的网络请求
    if (![page isEqualToString:@"0"]) {
        
        YTKNetHandle *api1 = [[YTKNetHandle alloc]initWithUrl:[NSString stringWithFormat:@"/Zx/lists.html?token=%@&page=%@",token, page] RegisterApiMethod:RequestMethodGet];
        [api1 startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            
            id result = [request.responseBody objectForKey:@"result"];
            page = result[@"nextPage"];
            if ([request.responseBody[@"error"] isEqualToString:@"0"]) {
                
                NSArray *arr = result[@"data"];
                for (NSDictionary *dic in arr) {
                    InformationModel *information = [[InformationModel alloc]init];
                    [information setValuesForKeysWithDictionary:dic];
                    [self.listArr addObject:information];
                    
                }
                if (arr.count == 0) {
                    UIImageView *view = [[UIImageView alloc]initWithFrame:_tableView.frame];
                    view.image = [UIImage imageNamed:@"缺省页"];
                    _tableView.backgroundView = view;
                }else{
                    _tableView.backgroundView = [[UIView alloc]initWithFrame:_tableView.frame];
                }

//                [_tableView reloadData];
                
            }else{
                NSLog(@"%@", result[@"msg"]);
                
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
    }else{
        aler = [[UIAlertView alloc]initWithTitle:@"提示" message:@"没有更多数据" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [aler show];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) userInfo:nil repeats:NO];
        
    
    }
    

}
- (void)time
{

    [aler dismissWithClickedButtonIndex:0 animated:YES];

}
- (void)tapImageV:(UITapGestureRecognizer *)tap
{
    for (int i = 0; i < _tapArr.count; i++) {
        if ([_tapArr[i] isEqual:tap]) {
            if (i == _tapArr.count - 1) {
                NSString *str = _idArr[0];
                InformationDetailViewController *detail = [[InformationDetailViewController alloc]init];
                detail.myId = str;
                [self.navigationController pushViewController:detail animated:YES];
            }else{
            
            
                NSString *str = _idArr[i];
                InformationDetailViewController *detail = [[InformationDetailViewController alloc]init];
                
                detail.myId = str;
                [self.navigationController pushViewController:detail animated:YES];
            }
            

        }
    }

}
#warning 刷新方法

//开始刷新自定义方法
- (void)setupRefresh
{
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    //一些设置
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
//    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
//    self.tableView.headerRefreshingText = @"刷新中。。。";
//    
//    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
//    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
//    self.tableView.footerRefreshingText = @"加载中。。。";
}
//下拉刷新
- (void)headerRereshing
{
    [self.listArr removeAllObjects];
    page = @"1";
    [self netHandle];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_tableView reloadData];
        //2.结束刷新
        [self.tableView headerEndRefreshing];
    });;
    
}
//上拉加载
- (void)footerRereshing
{
    
    [self netHandle];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_tableView reloadData];
        //2,结束刷新
        [self.tableView footerEndRefreshing];
    });;
}

#warning tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 20)];
    view.backgroundColor = [UIColor huiseColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.listArr.count;
//    return 10;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    InformationModel *information = self.listArr[indexPath.section];
    if (information.img.length != 0) {
        
        InformationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.titleLabel.text = information.name;
        if (information.img != nil) {
            
            [cell.imageV sd_setImageWithURL:[NSURL URLWithString:information.img] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        }
        cell.timeLabel.text = information.create_datetime_str;
        cell.numberLabel.text = information.is_hot;
        return cell;
    }else{
    
        InformationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.titleLabel.text = information.name;
        cell.timeLabel.text = information.create_datetime_str;
        cell.numberLabel.text = information.is_hot;
        return cell;

    
    
    }
 
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    InformationDetailViewController *detail = [[InformationDetailViewController alloc]init];
    InformationModel *model = self.listArr[indexPath.section];
    detail.myId = model.myId;
    [self.navigationController pushViewController:detail animated:YES];

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
